//
//  ZXHomeViewController.m
//  ZXOCWeiBo
//
//  Created by mac on 15/11/28.
//  Copyright © 2015年 itcast. All rights reserved.
//

#import "ZXHomeViewController.h"
#import "UIBarButtonItem+ZXExtension.h"
#import "ZXTooController.h"
#import "ZXTitleBtn.h"
#import "ZXPopController.h"
#import "ZXAccount.h"
#import "ZXStatuses.h"
#import "ZXUser.h"
#import "ZXFooterView.h"
#import "ZXHomeStatusParam.h"
#import "ZXHomeStatusResult.h"
#import "ZXStatusTool.h"
#import "ZXUserTool.h"
#import "ZXUserInfoParam.h"
#import "ZXUserInfoResult.h"
#import "ZXStatusCellFrm.h"
#import "ZXStatusCell.h"

@interface ZXHomeViewController ()

/**
 *  所以微博数据，里面存放ZXstatutes模型
 */
//@property(nonatomic,strong)NSMutableArray* statutes;
/**
 *  所以微博数据，里面存放ZXstatutesCellFrm模型
 */
@property(nonatomic,strong)NSMutableArray* statutesCellFrms;

@property(nonatomic,strong)ZXPopController* popControl;

@property(nonatomic,strong)ZXFooterView* footerView;


@property(nonatomic,strong)ZXTitleBtn* titleBtn;


/**
 *  系统的刷新控件
 */
@property(nonatomic,weak)UIRefreshControl * refreshControl;

@end

@implementation ZXHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //初始导航条控件
    [self setupNavigationBar];
   
    //添加系统刷新控件
    [self setupRefresh];
    
    //加载新的微博数据
    [self loadNewStatusesWithSinceID:@"0"];
    
//    加载用户的信息
    [self showuserInfo];
    
    self.view.backgroundColor = [UIColor lightGrayColor];
    
//    [SVProgressHUD showWithStatus:@"正在拼命加载数据。。。" maskType:SVProgressHUDMaskTypeGradient];
}
#pragma mark 初始控件
#pragma mark 初始导航条控件
-(void)setupNavigationBar
{
    //设置nav的左边按钮它需要一个UIBarButtonItem类型的按钮
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem barBtnItemWithNmlImg:@"navigationbar_friendsearch" hltImg:@"navigationbar_friendsearch_highlighted" target:self action:@selector(friendsearchBtnClick)];
    
    //设置导航条右两边按钮
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem barBtnItemWithNmlImg:@"navigationbar_pop" hltImg:@"navigationbar_pop_highlighted" target:self action:@selector(qrcScan)];
    
    self.title = @"首页";
    
    //创建按钮
    ZXTitleBtn * titleBtn = [ZXTitleBtn buttonWithType:UIButtonTypeCustom];
    self.titleBtn = titleBtn;
   
    [titleBtn sizeToFit];
    
    //    titleBtn.bounds = CGRectMake(0, 0, 100, 30);
    self.navigationItem.titleView = titleBtn;
    
    [titleBtn addTarget:self action:@selector(titleBtnClick:) forControlEvents:UIControlEventTouchUpInside];
}
//添加底部View
-(void)setupFooterView
{
    if (!_footerView)
    {
        ZXLog(@"创建了footer");
        ZXFooterView * footerView = [ZXFooterView footerView];
        footerView.w = self.view.w;
        self.tableView.tableFooterView = footerView;
        
        self.footerView = footerView;
    }
}
//刷新控件
-(void)setupRefresh
{
    //创建菊花
    UIRefreshControl * refreshcontrol = [[UIRefreshControl alloc]init];
    
    self.refreshControl = refreshcontrol;
//    添加刷新事件
    [refreshcontrol addTarget:self action:@selector(startRefresh) forControlEvents:UIControlEventValueChanged];
    //添加菊花
    [self.tableView addSubview:refreshcontrol];
}

//加载用户信息
-(void)showuserInfo
{
    NSString * url = @"https://api.weibo.com/2/users/show.json";
    
    ZXUserInfoParam * params = [ZXUserInfoParam param];
    params.uid = [ZXAccount shareAccount].uid;
    
    [ZXUserTool userInfoWithUrl:url params:params success:^(ZXUserInfoResult *result) {
        [self.titleBtn setTitle:result.screen_name forState:UIControlStateNormal];
    } failure:^(NSError *error) {
        ZXLog(@"%@",error);
    }];
}

#pragma mark --加载最新数据
//监听刷新事件
-(void)startRefresh
{
    //获取当前应用里最新的微博的idStr
//    ZXStatuses * newStatuses = [self.statutes firstObject];
    ZXStatusCellFrm * cellFrm = [self.statutesCellFrms firstObject];
    ZXStatuses * firstStatus = cellFrm.statuses;
    [self loadNewStatusesWithSinceID:firstStatus.idstr];
}

/**
 *  返回ID比since_id大的微博
 */
-(void)loadNewStatusesWithSinceID:(NSString *)sinceID
{
    //获取微博数据的连接
    NSString * url = @"https://api.weibo.com/2/statuses/home_timeline.json";
    
    
    //发送的请求参数
    ZXHomeStatusParam * params = [ZXHomeStatusParam param];
    params.since_id = @([sinceID longLongValue]);
    
    [ZXStatusTool homeStatusWithUrl:url params:params success:^(ZXHomeStatusResult *result) {
//        里面是ZXStatus
        NSArray * statusArr = result.statuses;
        
        NSMutableArray * statusCellFrmArr = [NSMutableArray array];
        for (ZXStatuses * status in statusArr)
        {
            ZXStatusCellFrm * statusCellFrm = [[ZXStatusCellFrm alloc]init];
            statusCellFrm.statuses = status;
            [statusCellFrmArr addObject:statusCellFrm];
        }
        
        NSIndexSet * set = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, statusCellFrmArr.count)];
        //将数据插入到最前面
        [self.statutesCellFrms insertObjects:statusCellFrmArr atIndexes:set];
        
        //        拼接到self.statutes 中 addObjectsFromArray这个方法是将数据插入到后面，要是刷新的时候，新数据也会添加到最后面，不能先显示在第一条数据的位置，所以我们要换方法
        //        [self.statutes addObjectsFromArray:statuses];
        //将数据插入到哪里，插入几条
//        NSIndexSet * set = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, result.statuses.count)];
//        //将数据插入到最前面
//        [self.statutes insertObjects:result.statuses atIndexes:set];
        
        //3.刷新表格
        [self.tableView reloadData];
        
        //4.结束系统的刷新控件
        [self.refreshControl endRefreshing];
        
        //有数据时才来创建这个底部的控件
        if (self.statutesCellFrms.count > 0 )
        {
            //添加底部View
            [self setupFooterView];
        }
        
        //显示微博条数的横幅
        [self showStatusCountBanner:result.statuses.count];
        

    } failure:^(NSError *error) {
        ZXLog(@"%@",error);
    }];

}

#pragma mark ---scrollVIew的代理方法

//当拖动是的时候会调用这个方法
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    //获取scrollView偏移了多少
    CGFloat offsetY = scrollView.contentOffset.y;
    
//    ZXLog(@"偏移值%f",offsetY);
    
    //    ZXLog(@"contentSizeHeight : %f",self.tableView.contentSize.height);
    
    //获取整个内容的高度
    CGFloat contentSizeHeight = self.tableView.contentSize.height;
    
    //获得整个scrollView的高度也就是tableView的高度
    CGFloat sceollViewHeight = scrollView.h;
    
    //    他们的差值
    CGFloat delta = contentSizeHeight - sceollViewHeight + 49 + 44;
//    ZXLog(@"差值%f",delta);
    //如果差值为负的直接返回
    if (delta < 0) {
        return;
    }
    
    if (offsetY > delta && !self.footerView.isLoading)
    {
        self.footerView.loading = YES;
        ZXLog(@"刷新");
        
        //加载更多数据
        [self loadMoreStatuses];
    }
}
//监听上啦刷新
-(void)loadMoreStatuses
{
    ZXLog(@"");
    //获取微博数据的连接
    NSString * url = @"https://api.weibo.com/2/statuses/home_timeline.json";
    
    //请求参数
    ZXHomeStatusParam * params = [ZXHomeStatusParam param];
    
    //若指定此参数，则返回ID小于或等于max_id的微博，默认为0。
    ZXStatusCellFrm * cellFrm = [self.statutesCellFrms lastObject];
    ZXStatuses * lastStatuses = cellFrm.statuses;
    params.max_id = @([lastStatuses.idstr longLongValue] - 1);
    
    [ZXStatusTool homeStatusWithUrl:url params:params success:^(ZXHomeStatusResult *result) {
    
        NSMutableArray * cellFrmArr = [NSMutableArray array];
        for (ZXStatuses * status in result.statuses)
        {
            ZXStatusCellFrm * cellFrm = [[ZXStatusCellFrm alloc]init];
            cellFrm.statuses = status;
            [cellFrmArr addObject:cellFrm];
        }
        
        [self.statutesCellFrms addObjectsFromArray:cellFrmArr];
        
        //3.刷新表格
        [self.tableView reloadData];
        
        //4.结束系统的刷新控件
        self.footerView.loading = NO;
    } failure:^(NSError *error) {
        ZXLog(@"%@",error);
    }];
}
#pragma mark ---私有方法
#pragma mark ---监听按钮的点击
//标题按钮点击
-(void)titleBtnClick:(ZXTitleBtn *)btn
{
    //没必要每次都来创建一个popControl，相当于懒加载
    if (!self.popControl)
    {
        //    MethodLog
        UIButton * contentView = [[UIButton alloc]init];
        contentView.bounds = CGRectMake(0, 0, 150, 150);
        contentView.backgroundColor = [UIColor redColor];
        
        //初始化popcontrol
        ZXPopController *popControl = [[ZXPopController alloc]initWithContenView:contentView];
        popControl.alpha = 0.5;
        
        [contentView addTarget:self action:@selector(Click) forControlEvents:UIControlEventTouchUpInside];
        
        self.popControl = popControl;
    }
    //展现
    [self.popControl showInView:btn position:ZXPopViewPosltionBottomCenter];
}

#pragma mark ---popView内部控件事件
-(void)Click
{
    [self.popControl dissmiss];
}
#pragma mark ---好友搜索按钮事件
-(void)friendsearchBtnClick{
    ZXTooController * two = [[ZXTooController alloc]init];
    
    [self.navigationController pushViewController:two animated:YES];
}
#pragma mark ---二维码扫描事件
-(void)qrcScan{
//    NSLog(@"%s",__func__);
}


#pragma mark ----数据源方法

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.statutesCellFrms.count;
}

//设置cell的高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
//    设置cell的高度
    ZXStatusCellFrm * cellFrm = self.statutesCellFrms[indexPath.row];
    return [cellFrm cellHeigt];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//    static NSString *ID = @"ID";
//    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:ID];
//    if (!cell)
//    {
//        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
//    }
//    
//    //获取微博相应属性
//    ZXStatuses * statuses = self.statutes[indexPath.row];
//    //设置微博正文
//    cell.textLabel.text = statuses.text;
//    //设置用户名
//    cell.detailTextLabel.text = statuses.user.screen_name;
//    
//    ZXLog(@"转发微博的内容%@",statuses.retweeted_status);
//    //设置头像
//    
////    placeholderImage占位图标
//    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:statuses.user.profile_image_url] placeholderImage:[UIImage imageNamed:@"hot_status"]];
    
    ZXStatusCell * cell = [ZXStatusCell cellWithTableView:tableView];
    cell.statusCellFrm = self.statutesCellFrms[indexPath.row];
    return  cell;
}

#pragma mark ---显示魏碧波条数的横幅
/**
 *  显示魏碧波条数的横幅
 */
-(void)showStatusCountBanner:(NSInteger)count
{
    NSString * bannerStr = @"无最新的微博数据";
    if (count > 0)
    {
        bannerStr = [NSString stringWithFormat:@"有%ld条微博数据",count];
    }
    
    UILabel * banner = [[UILabel alloc]init];
    banner.backgroundColor = [UIColor orangeColor];
    banner.text = bannerStr;
    banner.textAlignment = NSTextAlignmentCenter;
    banner.frame = CGRectMake(0, 20, self.view.w, 44);
    //添加banner insertSubview添加到什么 belowSubview到谁的下面
    [self.navigationController.view insertSubview:banner belowSubview:self.navigationController.navigationBar];
    
    //显示的时候有动画
    [UIView animateWithDuration:1.0 animations:^{
        
//        banner.y += 44;
        //平移到什么地方
        banner.transform = CGAffineTransformMakeTranslation(0, 44);
        
    } completion:^(BOOL finished) {
        //移除
         [UIView animateWithDuration:1.0 animations:^{
//             banner.y -= 44;
             //恢复到原来位置
             banner.transform = CGAffineTransformIdentity;
         } completion:^(BOOL finished) {
             //从父控件上移除
             [banner removeFromSuperview];
         }];
    }];
    
}

#pragma mark 公共方法
-(void)refresh
{
    if (self.refreshControl.isRefreshing) return;
    
    //让tableView往下移动 ， 让UIRefreshControl控件可以显示
    [self.tableView setContentOffset:CGPointMake(0, -64 - 44 * 2) animated:YES];
    
    //调用UIRefreshControl的beginRefresh方法，然后就会转
    [self.refreshControl beginRefreshing];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self startRefresh];
    });
}

#pragma mark 懒加载
//-(NSMutableArray *)statutes
//{
//    if (!_statutes)
//    {
//        _statutes = [NSMutableArray array];
//    }
//    return  _statutes;
//}
-(NSMutableArray *)statutesCellFrms
{
    if (!_statutesCellFrms)
    {
        _statutesCellFrms = [NSMutableArray array];
    }
    return  _statutesCellFrms;
}

@end
